package com.example.demo.groovy;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import java.io.File;
import java.io.IOException;

/**
 * @Author: wn
 * @date 2022年09月19日 17:49
 */
public class GroovyIntoJavaDemo1 {

    //测试次数
    private static final int num = 10000;

    public static void main(String[] args) throws IOException, ResourceException, ScriptException {

        /*
        GroovyClassLoader
         */
        long start = System.currentTimeMillis();
        GroovyClassLoader loader =  new GroovyClassLoader();
        Class aClass = loader.parseClass(new File("src/main/java/com/example/demo/groovy/CycleDemo.groovy"));
        try {
            GroovyObject instance = (GroovyObject) aClass.newInstance();
            instance.invokeMethod("cycle",num);

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis()-start;

        /*
        GroovyShell
         */
        long start1 = System.currentTimeMillis();

        new GroovyShell().parse( new File( "src/main/java/com/example/demo/groovy/CycleDemo.groovy" ) )
                .invokeMethod("cycle",num);

        long end1 = System.currentTimeMillis()-start1;

        /*
        GroovyScriptEngine
         */
        long start2 = System.currentTimeMillis();

        Class script = new GroovyScriptEngine("src/main/java/com/example/demo/groovy/")
                .loadScriptByName("CycleDemo.groovy");
        try {
            Script instance =(Script) script.newInstance();
            instance.invokeMethod ("cycle",new Object[]{num});
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        long end2 = System.currentTimeMillis()-start2;

        System.out.println(" GroovyClassLoader时间："+ end );
        System.out.println(" GroovyShell时间："+ end1 );
        System.out.println(" GroovyScriptEngine时间："+ end2 );

    }

}